const { app, protocol } = require('electron');
const { join } = require('path');
const fs = require('fs');
const { parse: urlParse } = require('url');

function registerVueFile(urlScheme, vueDir) {
    protocol.registerSchemesAsPrivileged([
        {
            scheme: urlScheme,
            privileges: {
                bypassCSP: true,
            },
        },
    ]);
    app.on('ready', () => {
        protocol.registerFileProtocol(urlScheme, (require, callback) => {
            const cache = {};
            let { host, pathname } = urlParse(require.url);
            pathname = pathname || '';
            if (host !== 'dist') {
                callback({ error: 'dist error.' });
                return;
            }
            const pathSegments = pathname
                .split('/')
                .filter((segment) => segment !== '');
            const filepath = join(
                join(__dirname || resolve(dirname('')), '.', vueDir),
                ...pathSegments
            );
            if (!cache[require.url]) {
                try {
                    fs.accessSync(filepath);

                    if (fs.statSync(filepath).isFile()) {
                        cache[require.url] = filepath;
                    }
                } catch (err) { }
            }
            let indexPath = undefined;
            indexPath =
                indexPath ||
                join(
                    join(__dirname || resolve(dirname('')), '.', vueDir),
                    'index.html'
                );
            callback({ path: cache[require.url] || indexPath });
        });
    });
}

module.exports.registerVueFile = registerVueFile;
